#include "SynergyProxyModel.h"



#include <ItemModel.h>
#include <ItemReference.h>



#include <QDebug>



namespace
{
QString SKILL_GROUP_ID = ".Skill";
}


SynergyProxyModel::SynergyProxyModel(QObject *parent) :
    ReferenceProxyModel(parent)
{
}



bool SynergyProxyModel::setData(const QModelIndex &proxyIndex, const QVariant &value, int role)
{
    Q_UNUSED(value);

    if (role != Qt::CheckStateRole) return false;

    if (proxyIndex.data(Qt::CheckStateRole).toBool())
    {
        removeReference(proxyIndex);
        return true;
    }

    QModelIndex sourceRef = createReference(proxyIndex, ItemReference::SynergyRef);
    if (!sourceRef.isValid()) return false; // source reference was not created for any reason...

    return true;
}



Qt::ItemFlags SynergyProxyModel::flags(const QModelIndex &proxyIndex) const
{
    if (!proxyIndex.isValid()) return Qt::NoItemFlags;

    QModelIndex sourceIndex = mapToSource(proxyIndex);
    if (!sourceIndex.isValid()) return Qt::NoItemFlags;
    if (!m_sourceTarget.isValid()) return Qt::NoItemFlags;

    QModelIndex sourceId = sourceIndex.sibling(sourceIndex.row(), AbstractItem::IdData);
    QModelIndex targetId = m_sourceTarget.sibling(m_sourceTarget.row(), AbstractItem::IdData);

    if (!sourceId.isValid() || !targetId.isValid()) return Qt::NoItemFlags;
    if (sourceId.data(Qt::EditRole) == targetId.data(Qt::EditRole)) return Qt::NoItemFlags;

    return Qt::ItemIsUserCheckable | Qt::ItemIsEnabled;
}



void SynergyProxyModel::remap()
{
    clear();

    ItemModel* model = dynamic_cast<ItemModel*>(sourceModel());
    if (!model) return;

    QModelIndex sourceGroupName = model->index(0,AbstractItem::NameData, QModelIndex());
    while (sourceGroupName.isValid())
    {
        QModelIndex sourceGroupId = sourceGroupName.sibling(sourceGroupName.row(), AbstractItem::IdData);
        if (!sourceGroupId.data(Qt::EditRole).toString().contains(SKILL_GROUP_ID))
        {
            sourceGroupName = sourceGroupName.sibling(sourceGroupName.row()+1, AbstractItem::NameData);
            continue;
        }

        QModelIndex sourceItemName = sourceGroupName.child(0, AbstractItem::NameData);
        while (sourceItemName.isValid())
        {
            ProxyIndex proxyItemName = createIndex(sourceItemName.row(), NameField, sourceItemName.internalPointer());
            addMapping(sourceItemName, proxyItemName);

            sourceItemName = sourceItemName.sibling(sourceItemName.row()+1, AbstractItem::NameData);
        }

        break;
    }
}
